package cn.wolfcode.web.controller;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.DateUtil;
import cn.wolfcode.util.UserUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Ordering;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.HttpRequestHandlerServlet;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;
    //如果有1W个请求会一直访问redis，为了减少对redis的访问在redis外面又进行了判断，采用了分段锁
    public static ConcurrentHashMap<Long,Boolean> local_flag = new ConcurrentHashMap<Long, Boolean>();
    @RequestMapping("/doSeckill")
    @RequireLogin
    public Result<String> doSeckill(Long seckillId, int time, HttpServletRequest request){
        //1.判断是否登录
        //2.参数校验
        if (StringUtils.isEmpty(seckillId+"") && StringUtils.isEmpty(time+"")){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //判断本地标识，如果本地标识为true，redis已经减到了负数，直接抛出异常
        Boolean aBoolean = local_flag.get(seckillId);
        if (aBoolean!=null && aBoolean){
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //3.判断是否在秒杀活动时间范围内
        SeckillProductVo vo = seckillProductService.queryByTimeAndSid(time, seckillId);
        /*Date startDate = vo.getStartDate();
        boolean isTime = DateUtil.isLegalTime(startDate, time);
        if (!isTime) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }*/
        //4.判断库存是否足够
        if (vo.getStockCount() < 0) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //5.判断用户是否有重复下单
        //set seckillOrderset:time    phone:seckillId true 为true说明重复下单
        String token = request.getHeader("token");
        UserInfo userInfo = UserUtil.getUser(redisTemplate, token);
        Boolean member = redisTemplate.opsForSet().
                isMember(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time + ""), userInfo.getPhone() + ":" + seckillId);
        if (member) {
            throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        }
        //获取Redis中的库存数
        Long count = redisTemplate.opsForHash().
                increment(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time + ""),
                        seckillId + "", -1);
        if (count < 0){
            local_flag.put(seckillId,true);
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //6.秒杀业务逻辑
        //6.1减少真实库存
        //6.2创建订单并且把订单保存到数据库中t_order_info
        //6.3往redis存一个数据为重复下单做铺垫
        /*String orderNo = orderInfoService.doSeckill(seckillId,time,userInfo.getPhone());*/
        //用异步去实现
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setSeckillId(seckillId);
        orderMessage.setTime(time);
        orderMessage.setToken(token);
        orderMessage.setUserPhone(userInfo.getPhone());
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_PEDDING_TOPIC,orderMessage);
        return Result.success("正在抢购中，稍后会通知您");
    }

    @RequestMapping("/find")
    public Result<OrderInfo> find(String orderNo,HttpServletRequest request){
        if (StringUtils.isEmpty(orderNo)) {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        //从redis中拿取订单数据
        //如果等于空，可能是别人伪造的订单号
        if (orderInfo == null){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        //当前登录用户只能看到自己的订单信息
        String token = request.getHeader("token");
        UserInfo user = UserUtil.getUser(redisTemplate, token);
        if (!user.getPhone().equals(orderInfo.getUserId())){
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }
        return Result.success(orderInfo);
    }

}
